<?php
/*
 *  微信接口
    华视文化2.0
    CopyRight 2014 All Rights Reserved
*/
header("content-type:text/html;charset=UTF-8");
define("TOKEN", "weixin");

include_once('DB.php');

$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
	$wechatObj->responseMsg();
}else{
    $wechatObj->valid();
}

class wechatCallbackapiTest
{
    public $DB;
    
    //构造函数
//    public function __construct() {
//	$this->DB = new DB();
//    }
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $this->logger("R ".$postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                case "location":
                    $result = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    $result = $this->receiveVoice($postObj);
                    break;
                case "video":
                    $result = $this->receiveVideo($postObj);
                    break;
                case "link":
                    $result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknow msg type: ".$RX_TYPE;
                    break;
            }
            $this->logger("T ".$result);
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
          case "subscribe":
			
            //如果是关注信息
	    if(check_user($object->FromUserName))
	   {
		//关注绑定的欢迎词
		$content = "欢迎关注华视文化，您已经绑定了员工通讯录。\n请回复'YGCX'进行员工查询\n请回复'YGGX'进行员工更新\n退出请回复'EXIT'";
	    }
	    else{
				
		$content = "欢迎关注华视文化置家好人卡，您还没有绑定员工通讯录，请回复“BD”进行通讯录绑定";
                }
                $content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
						
                break;
            case "unsubscribe":
                $content = "取消关注";
                break;
            case "SCAN":
                $content = "扫描场景 ".$object->EventKey;
                break;
            case "CLICK":
             //菜单点击事件推送
		   //用户点击了自定义的菜单，然后可以获取EventKey，就是在创建菜单时设置的菜单关键字
                switch ($object->EventKey)
                {
                    case "COMPANY":
                        $content = "华视文化提供互联网相关产品与服务。";
                        break;
		//获取菜单关键字
		    case "置家帮":
		         $content[] = array("Title"=>"装修攻略", "Description"=>"装修攻略", "PicUrl"=>"http://wechat.zhijia365.com/upload/img/top.jpg", "Url" =>"http://wechat.zhijia365.com/zhijiabang/index.php"); 
                        
                        if(is_array($content)){
                        if (isset($content[0]['PicUrl'])){
                            $result = $this->transmitNews($object, $content);
                        }else if (isset($content['MusicUrl'])){
                            $result = $this->transmitMusic($object, $content);
                        }
                        }else{
                            $result = $this->transmitText($object, $content);
                        }
                        return $result;
                        
                        
			break;
		     case "置家366":
			$content = "您点击了置家366";
			break;
		     case "置家367":
			$content = "您点击了置家367";
			break;
						
		     case "置家E1":
			$content = "您点击了置家E1";
			break;
                    case "置家E2":
			$content = "您点击了置家E2";
			break;
		    case "置家E3":
			$content = "您点击了置家E3";
			break;	
		   case "华视文化":
			$content = "您点击了华视文化";
			break;
						
                    default:
                        $content = "点击菜单：".$object->EventKey;
                        break;

                }
                break;
            case "LOCATION":
                $content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //保存上一步操作
    private function baocunStep($DB,$keyword){
         $DB =  new DB();
         $dataArray = array('order_name'=>$keyword);
         //$DB->update("order",$dataArray);
        
    }
    
    //调取上一步指令
     private function openStep($DB,$keyword){
         $DB =  new DB();
         $dataArray = array('order_name'=>$keyword);
         //$DB->update("order",$dataArray);
        
    }
    
     
     private function receiveText($object)
    {

        $keyword = trim($object->Content);
        $fromUsername = $object->FromUserName;
       
        if( $keyword=="置家帮"){
        $content[] = array("Title"=>"装修攻略", "Description"=>"装修攻略", "PicUrl"=>"http://wechat.zhijia365.com/upload/img/top.jpg", "Url" =>"http://wechat.zhijia365.com/zhijiabang/index.php"); 
        }
        
       //新建数据库操作对象
        $DB =  new DB();
         
//通讯录功能
        //验证用户是否第一次发信息，如果用户第一次发信息，为用户创建一行记录
        //员工查询
 //第一步
        if($keyword=="ygcx"){
            //如果指令表中该用户没有指令，插入
            $query = $DB->get_all("select * from user_order where openid='{$fromUsername}'");   
            //如果没有就插入
            if(!$query){
            $dataArray = array('order_name'=>$keyword,'openid'=>$fromUsername);
            $bool = $DB->insert("user_order",$dataArray); 
            $content = "请输入gh进行工号查询\n或者输入xm进行姓名查询\n输入exit退出";
           }
           else{
              $content = "请输入gh进行工号查询\n或者输入xm进行姓名查询\n输入exit退出";
           }
        }
//如果意外退出exit
       if($keyword=="exit"){
            $DB->delete("user_order","openid='{$fromUsername}'");
           $content = "您已经退出了员工通讯录";
 
        }
//        else {
    //第三步
              $query2 =  $DB->get_one("select order_name from user_order where openid='{$fromUsername}'");
               if($query2['order_name']=="gh"||$query2['order_name']=="xm"){
                   switch($query2['order_name']){
                       case xm:
                          //进行按姓名的查询:
                          $name =  $keyword ;
                          $xmResult =  $DB->get_one("select * from roster where roster_name='{$name}'");
                          //可能是用户进行别名查询
                          if(!$xmResult){
                              $xmResult =  $DB->get_one("select * from roster where roster_rname='{$name}' and status =1");
                          }
                          if($xmResult['roster_name']){
                          $content[] = array("Title"=>$xmResult['roster_name']."__电话".$xmResult['roster_mp'], "Description"=>"员工详细信息:".$xmResult['roster_name'], "PicUrl"=>$xmResult['roster_pic'], "Url" =>"http://wechat.zhijia365.com/roster/list.php?name='{$name}'"); 
                     
                          //显示查询结果之后删除用户数据      
                          $DB->delete("user_order","openid='{$fromUsername}'");
                          }else {
                              $content = "姓名输入错误，请重新输入";
                          }
                           break;
                       case gh:
                           //进行按工号的查询
                           $number =  $keyword;
                           $ghResult =  $DB->get_one("select * from roster where roster_number='{$number}' and status =1");

                           if($ghResult['roster_name']){
                           $content[] = array("Title"=>$ghResult['roster_name']."__电话".$ghResult['roster_mp'], "Description"=>"员工详细信息:".$ghResult['roster_name'], "PicUrl"=>$ghResult['roster_pic'], "Url" =>"http://wechat.zhijia365.com/roster/list.php?number={$number}");  

                           //显示查询结果之后删除用户数据      
                           $DB->delete("user_order","openid='{$fromUsername}'");
                           }else{
                                $content = "工号输入错误，请重新输入";
                           }
                           break;
                       default:
                           break;
                   }
            }

     //第二步
            //继续进行操作，也可以判断指令
            $query =  $DB->get_one("select order_name from user_order where openid='{$fromUsername}'");
            //更新命令   
              if($query['order_name']=="ygcx"){
                 $dataArray = array('order_name'=>$keyword,'openid'=>$fromUsername);
                 //更新用户上一步的命令
                 $bool = $DB->update("user_order",$dataArray,"openid='$fromUsername'"); 

                 //对操作进行判断
                 //更新成功
                 if($bool){
                     switch($keyword){
                         //按照姓名查询
                         case "xm":
                              $content = "请输入姓名：\n例如：李桦或者lh\n输入exit退出";
                             break;
                         //按照工号查询
                         case "gh":
                              $content = "请输入工号：\n例如：110\n输入exit退出";
                             break;
                         default:
                             break;   
                     }
                 }
            }
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
//        }
        
		
//        $DB =  new DB();
//        
//        if($keyword){
//
//            //查询reply回复消息表
//            $query = $DB->query("select * from reply");   
//            //key为数据库存储的关键字
//            
//          while($row=mysql_fetch_array($query)){  
//              if($keyword==$row['reply_key'])
//              {
//                  //证明表中含有所输入的关键字
//                  //下面验证回复消息的类型
//                  switch($row['type']){
//                      //证明是文本消息
//                      case 1:
//                          $content = "回复文本消息：".$row['reply_value'];
//                          break;
//                      
//                      //证明是图文回复
//                      case 2:
//                           $content[] = array("Title"=>$row['key'], "Description"=>$row['key'], "PicUrl"=>$row['pic'], "Url" =>$row['link']);
//                        
//                          break;
//                      
//                      //证明是音乐回复
//                      case 3:
//                            $content = array("Title"=>"最炫民族风", "Description"=>"歌手：凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
//                          break;
//                      
//                      //证明是链接回复
//                      case 4:
//                          break;
//                      
//                      //其他 直接退出
//                      default :
//                          
//                          
//                          break;
//                      
//                  }
//                  
//                 break;
//              }
//              
//          }
//        }
//        //检索是不是包含大转盘的关键字
//  
//       $res_list = $DB->get_all("select * from zhuanpan");
//       foreach($res_list as $value){
//           if($value[zhuanpan_key]==$keyword){
//               
//               $content[] = array("Title"=>"幸运大转盘活动开始了", "Description"=>"活动欢迎大家尽情参加！", "PicUrl"=>"http://wechat.zhijia365.com/img/zhuanpan.jpg", "Url" =>"http://wechat.zhijia365.com/data/weixin/zhuanpan/index.php?openid=".$object->FromUserName); 
//           }
//           
//       }
//       
//       $res_guaguaka = $DB->get_all("select * from guaguaka");
//       foreach($res_guaguaka as $value){
//           if($value[guaguaka_key]==$keyword){
//               
//               $content[] = array("Title"=>"刮刮卡-大奖刮出来", "Description"=>"活动欢迎大家尽情参加！", "PicUrl"=>"http://wechat.zhijia365.com/img/guaguaka.jpg", "Url" =>"http://wechat.zhijia365.com/data/weixin/guaguaka/index.php?openid=".$object->FromUserName); 
//           }
//           
//       }

       
//         switch ($keyword){
//             //	//输入大转盘
//                case "第三方":
//		$content[] = array("Title"=>"大转盘", "Description"=>"大转盘", "PicUrl"=>"http://wechat.zhijia365.com/img/logo.jpg", "Url" =>"http://wechat.zhijia365.com/data/weixin/zhuanpan/index.php");
//		break;
//             
//                default:
//                $content = "当前时间：".date("Y-m-d H:i:s",time());
//                break;
//             
//        
//         }
//        switch ($keyword)
//        {
//            case "文本":
//                $content = "这是个文本消a息". $value;
//                               
//            break;
//						
//	    case "图文":
//            case "单图文":
//                $content[] = array("Title"=>"单图文标题", "Description"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
//				
//				
//                break;
//            case "多图文":
//                $content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
//                $content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
//                $content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
//                break;
//            case "音乐":
//                $content = array("Title"=>"最炫民族风", "Description"=>"歌手：凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3");
//                break;
//				
//			
//	//输入大转盘
//	case "大转盘":
//		$content[] = array("Title"=>"大转盘", "Description"=>"大转盘", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://1.huashiwhwx.sinaapp.com/zhuanpan/index.htm");
//		break;
//	
//	//刮刮卡
//		case "刮刮卡":
//		$content[] = array("Title"=>"刮刮卡", "Description"=>"刮刮卡", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://1.huashiwhwx.sinaapp.com/guaguaka/index.html");
//		break;
//	//砸金蛋 
//		case "砸金蛋":
//		$content[] = array("Title"=>"砸金蛋", "Description"=>"砸金蛋", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://1.huashiwhwx.sinaapp.com/zajindan/index.html");
//		break;
//			 			
//            default:
//                $content = "当前时间：".date("Y-m-d H:i:s",time());
//                break;
//        }
		   
        if(is_array($content)){
            if (isset($content[0]['PicUrl'])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

    private function receiveImage($object)
    {
        $content = array("MediaId"=>$object->MediaId);
        $result = $this->transmitImage($object, $content);
        return $result;
    }

    private function receiveLocation($object)
    {
        $content = "你发送的是位置，纬度为：".$object->Location_X."；经度为：".$object->Location_Y."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    private function receiveVoice($object)
    {
        if (empty($object->Recognition)){
            $content = array("MediaId"=>$object->MediaId);
            $result = $this->transmitVoice($object, $content);
        }else{
            $content = "你刚才说的是：".$object->Recognition;
            $result = $this->transmitText($object, $content);
        }

        return $result;
    }

    private function receiveVideo($object)
    {
        $content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
        $result = $this->transmitVideo($object, $content);
        return $result;
    }

    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    private function transmitText($object, $content)
    {
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    private function transmitImage($object, $imageArray)
    {
        $itemTpl = "<Image>
    <MediaId><![CDATA[%s]]></MediaId>
</Image>";

        $item_str = sprintf($itemTpl, $imageArray['MediaId']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "<Voice>
    <MediaId><![CDATA[%s]]></MediaId>
</Voice>";

        $item_str = sprintf($itemTpl, $voiceArray['MediaId']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    private function transmitVideo($object, $videoArray)
    {
        $itemTpl = "<Video>
    <MediaId><![CDATA[%s]]></MediaId>
    <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
</Video>";

        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return;
        }
        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

    private function transmitMusic($object, $musicArray)
    {
        $itemTpl = "<Music>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
    <MusicUrl><![CDATA[%s]]></MusicUrl>
    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";

        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";

        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    private function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 10000;
            $log_filename = "log.xml";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }
}


?>